﻿using System;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Globalization;
using System.Reflection;
using System.Text.RegularExpressions;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace BookDownloader.Core
{
	public class Utility
	{
		public static void Decompress(FileInfo fi)
		{
			// Get the stream of the source file.
			using (FileStream inFile = fi.OpenRead())
			{
				// Get original file extension, for example
				// "doc" from report.doc.gz.
				string curFile = fi.FullName;
				string origName = curFile.Remove(curFile.Length -
				                                 fi.Extension.Length);

				//Create the decompressed file.
				using (FileStream outFile = File.Create(origName))
				{
					using (GZipStream Decompress = new GZipStream(inFile,
					                                              CompressionMode.Decompress))
					{
						// Copy the decompression stream 
						// into the output file.
						Decompress.CopyTo(outFile);

					}
				}
			}
		}

		public static string WorkingDirectoryName
		{
			get
			{
				//TODO: Do something 
				return ""; // Path.GetDirectoryName(Application.ExecutablePath); 
			}
		}

		public static DirectoryInfo GetDirectoryFromConfig(string key)
		{
			string basePath = ConfigurationManager.AppSettings[key];
			if (String.IsNullOrEmpty(basePath))
				basePath = key;
			DirectoryInfo dir = null;
			if (!Path.IsPathRooted(basePath))
			{
				dir = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, basePath));
			}
			else
			{
				dir = new DirectoryInfo(basePath);
			}
			return dir;
		}


		public static object CreateObjectFromMatch(Match match, Type type)
		{
			PropertyInfo[] props = type.GetProperties();
			object obj = Activator.CreateInstance(type);
			foreach (PropertyInfo prop in props)
			{
				prop.SetValue(obj, Convert.ChangeType(match.Groups[prop.Name].Value, prop.PropertyType), null);
			}
			return obj;
		}


	}
}
